//
//  MineMessageViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/1.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "MineMessageViewController.h"
#import "MineMessageTableViewCell.h"
#import "SystemMessageViewController.h"
#import "MessageModel.h"
#import "MessageItemModel.h"
#import "OthersMemberInfoModel.h"

@interface MineMessageViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *tableArray;
@property (nonatomic, strong) NSMutableArray *messageArr;

@property (nonatomic, strong) NSMutableArray *expertArr;
@property (nonatomic, strong) NSMutableArray *normalArr;

//@property (nonatomic, assign) BOOL isExpert;
@property (nonatomic, assign) BOOL msgCount;
@end

@implementation MineMessageViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        //_isExpert = NO;
        _msgCount = NO;
        _messageArr = [NSMutableArray array];
        _expertArr = [NSMutableArray array];
        _normalArr = [NSMutableArray array];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDataIfExpert) name:ReciveRongCloudMessage object:nil];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ReciveRongCloudMessage object:nil];
}

#pragma mark - Get
- (NSMutableArray *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
#pragma mark - ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"我的消息";
    [self hiddenShadowImage:NO];
    
    [self createTableView];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getDataIfExpert];
    
    [self clearRedDot];
}

#pragma mark -
static NSString *messageTableIdentifier = @"messageTableIdentifier";
- (void)createTableView {
    [self.tableView registerNib:[UINib nibWithNibName:@"MineMessageTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:messageTableIdentifier];
    [self.tableView clearExtendCellLine];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getDataIfExpert];
    }];

    [self.tableView.mj_footer setHidden:YES];
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetSuccess:(NSDictionary *)dics {
    
    // 数据列表
//    NSArray *arr = [[dics safeJsonObjectForKey:@"data"] safeJsonObjectForKey:@"list"];// dics[@"data"][@"list"];
//    [self.messageArr removeAllObjects];
//    for (NSDictionary *dataDic in arr) {
//        MessageModel *model = [MessageModel mj_objectWithKeyValues:dataDic];
//        [self.messageArr addObject:model];
//    }
    [self.messageArr removeAllObjects];
    MessageModel *model = [MessageModel mj_objectWithKeyValues:[dics safeJsonObjectForKey:@"data"]];
    model.msg = [[dics safeObjectForKey:@"msg"] boolValue];
    [self.messageArr addObjectsFromArray:model.list];
    self.msgCount = model.msg; // dics[@"data"][@"msg"];
    [self.tableView reloadData];
}

- (void)clearRedDot {
    [UserInfo shareInstance].user.showBadge = NO;
    [[UserInfo shareInstance] updateUserModel];
    [(AppDelegate *)[UIApplication sharedApplication].delegate updateBadgeValue:NO];
}

- (void)configureData {
    [self.tableArray removeAllObjects];
    
    MessageSystemModel *model = self.messageArr.firstObject;
    MessageItemModel *item = [[MessageItemModel alloc] init];
    item.modelType = MessageItemModelTypeForSystem;
    item.imageUrl = @"";
    item.title = @"系统消息";
    item.imagePlaceHolder = [UIImage imageNamed:@"xiaoxi"];
    item.messageCount = self.msgCount ? 1 : 0;
    item.subTitle = model.ititle.length > 0 ? model.ititle : @"暂无消息";
    item.time = model.createtime;
    [self.tableArray addObject:item];
    
    NSArray<QYSessionInfo*> *chatArray = [[[QYSDK sharedSDK] conversationManager] getSessionList];
    for (QYSessionInfo *conversation in chatArray) {
        MessageItemModel *experItem = [[MessageItemModel alloc] init];
        experItem.modelType = MessageItemModelTypeForNormal;
        experItem.messageCount = conversation.unreadCount;
        experItem.imageUrl = QiYuServiceHeader;
        experItem.title = QiYuServiceName;
        experItem.imagePlaceHolder = PlaceholderImageHeader;
        experItem.time = [NSString stringWithFormat:@"%f", conversation.lastMessageTimeStamp];
        
        switch (conversation.lastMessageType) {
            case QYMessageTypeText:
                experItem.subTitle = conversation.lastMessageText;
                break;
            case QYMessageTypeAudio:
                experItem.subTitle = @"[语音]";
                break;
            case QYMessageTypeImage:
                experItem.subTitle = @"[图片]";
                break;
            default:
                break;
        }
        
        [self.tableArray addObject:experItem];
    }
    /*
    NSArray *conversationListArr = [[RCIMClient sharedRCIMClient] getConversationList:@[@(ConversationType_PRIVATE)]];
    
    NSMutableArray *expertArr = [NSMutableArray array];
    NSMutableArray *normalArr = [NSMutableArray array];
    for (RCConversation *conversation in conversationListArr) {
        if ([conversation.targetId containsString:@"E"]) {
            [expertArr addObject:conversation];
        } else {
            [normalArr addObject:conversation];
        }
    }
    
//    RCConversation *expertConversation = expertArr.firstObject;
//    MessageItemModel *experItem = [[MessageItemModel alloc] init];
//    experItem.modelType = MessageItemModelTypeForExpert;
//    experItem.imageUrl = @"";
//    experItem.title = @"专家看货";
//    experItem.imagePlaceHolder = [UIImage imageNamed:@"specialist_ico"];
//    experItem.messageCount = expertConversation.unreadMessageCount;
//    experItem.subTitle = (expertConversation.unreadMessageCount == 0) ? @"暂无新消息" : @"有新消息";
//    experItem.time = [NSString stringWithFormat:@"%lld", (expertConversation.sentTime / 1000)];
//
//    [self.tableArray addObject:experItem];
    
    
    // normal list 数据
    for (RCConversation *conversation in normalArr) {
        RCUserInfo *userInfo = [[RCIM sharedRCIM] getUserInfoCache:conversation.targetId];

        MessageItemModel *item = [[MessageItemModel alloc] init];
        item.modelType = MessageItemModelTypeForNormal;
        item.messageCount = conversation.unreadMessageCount;
        item.targetId = conversation.targetId;
        item.imageUrl = userInfo.portraitUri;
        item.title = userInfo.name;
        item.imagePlaceHolder = PlaceholderImageHeader;
        item.time = [NSString stringWithFormat:@"%lld", (conversation.sentTime / 1000)];
     
        
        if ([conversation.lastestMessage isKindOfClass:[RCTextMessage class]]) {
            RCTextMessage *textMessage = (RCTextMessage *)conversation.lastestMessage;
            item.subTitle = textMessage.content;
        } else if ([conversation.lastestMessage isKindOfClass:[RCVoiceMessage class]]) {
            item.subTitle = @"[语音]";
        } else if ([conversation.lastestMessage isKindOfClass:[RCImageMessage class]]) {
            item.subTitle = @"[图片]";
        } else if ([conversation.lastestMessage isKindOfClass:[RCDLinkerMessage class]]) {
            item.subTitle = @"[商品链接]";
        }
            
        [self getOthersInfo:item];

//        if (userInfo.name.length == 0 || userInfo.portraitUri.length == 0) {
//            [self getOthersInfo:item];
//        }
        [self.tableArray addObject:item];
    }
     */
    
    [self.tableView reloadData];
}

- (void)configureExpertData {
    [self.tableArray removeAllObjects];
    
    /*
    NSArray *conversationListArr = [[RCIMClient sharedRCIMClient] getConversationList:@[@(ConversationType_PRIVATE)]];
    
    NSMutableArray *expertArr = [NSMutableArray array];
    NSMutableArray *normalArr = [NSMutableArray array];
    for (RCConversation *conversation in conversationListArr) {
        if ([conversation.targetId containsString:@"E"]) {
            [expertArr addObject:conversation];
        } else {
            [normalArr addObject:conversation];
        }
    }
    
    
    // normal list 数据
    for (RCConversation *conversation in expertArr) {
        RCUserInfo *userInfo = [[RCIM sharedRCIM] getUserInfoCache:conversation.targetId];
        
        MessageItemModel *item = [[MessageItemModel alloc] init];
        item.modelType = MessageItemModelTypeForNormal;
        item.messageCount = conversation.unreadMessageCount;
        item.targetId = conversation.targetId;
        item.imageUrl = userInfo.portraitUri;
        item.title = userInfo.name;
        item.imagePlaceHolder = PlaceholderImageHeader;
        item.time = [NSString stringWithFormat:@"%lld", (conversation.sentTime / 1000)];
        
        
        if ([conversation.lastestMessage isKindOfClass:[RCTextMessage class]]) {
            RCTextMessage *textMessage = (RCTextMessage *)conversation.lastestMessage;
            item.subTitle = textMessage.content;
        } else if ([conversation.lastestMessage isKindOfClass:[RCVoiceMessage class]]) {
            item.subTitle = @"[语音]";
        } else if ([conversation.lastestMessage isKindOfClass:[RCImageMessage class]]) {
            item.subTitle = @"[图片]";
        }
        [self getOthersInfo:item];

//        if (userInfo.name.length == 0 || userInfo.portraitUri.length == 0) {
//            [self getOthersInfo:item];
//        }
        [self.tableArray addObject:item];
    }
    */
    [self.tableView reloadData];
}

- (void)getDataIfExpert {
    [self getNetData];
    /*
    if (self.isExpert) {
        [self configureExpertData];
    } else {
        [self getNetData];
    }
     */
}

#pragma mark - 网络请求
- (void)getNetData {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:@"1" forKey:@"pageSize"];
    [dic setObject:@"1" forKey:@"pageNumber"];
    
    // 获取我的消息列表接口
    [MYAFNetworking POST:URL_Get_Infomation parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dics = responseObject;
            [self getNetSuccess:dics];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
        [self configureData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
        [self configureData];
    }];
}

- (void)getOthersInfo:(MessageItemModel *)item {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:item.targetId forKey:@"mid"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Other_Member_Info parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic  safeObjectForKey:@"code"];
        if ([code isEqualToString:@"200"]) {
            NSDictionary *modelDic = [responseDic safeJsonObjectForKey:@"data"];
            OthersMemberInfoModel *model = [OthersMemberInfoModel mj_objectWithKeyValues:modelDic];
            item.title = model.mnickname;
            item.imageUrl = model.mimg;
            
            /*
            // 更新本地融云个人数据
            RCUserInfo *updatedUserInfo =
            [[RCUserInfo alloc] initWithUserId:model.mid name:model.mnickname portrait:model.mimg];
            [[RCIM sharedRCIM]
             refreshUserInfoCache:updatedUserInfo
             withUserId:updatedUserInfo.userId];
             */
            
            [weakSelf.tableView  reloadData];
        } else {
            NSLog(@"请求失败");
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:messageTableIdentifier forIndexPath:indexPath];
    MessageItemModel *itemModel = [self.tableArray safeObjectAtIndex:indexPath.row];
    switch (itemModel.modelType) {
        case MessageItemModelTypeForSystem: {
            cell.numberLabel.hidden = !(itemModel.messageCount > 0);
            [cell.numberLabel setText:@""];
        } break;
        case MessageItemModelTypeForNormal: {
            cell.numberLabel.hidden = !(itemModel.messageCount > 0);
            [cell.numberLabel setText:[NSString stringWithFormat:@"%ld", (long)itemModel.messageCount]];
        } break;
        case MessageItemModelTypeForExpert: {
            cell.numberLabel.hidden = !(itemModel.messageCount > 0);
            [cell.numberLabel setText:@""];
        } break;
            
        default:
            break;
    }
    [cell.titleLabel setText:itemModel.title];
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:itemModel.imageUrl] placeholderImage:itemModel.imagePlaceHolder];
    [cell.contentLabel setText:itemModel.subTitle];
    [cell.timeLabel setText:itemModel.time.integerValue > 0 ? [NSString countTimeTransfoWithString:itemModel.time] : @""];
    
    [cell.contentView layoutSubviews];
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 75.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MessageItemModel *item = [self.tableArray safeObjectAtIndex:indexPath.row];
    switch (item.modelType) {
        case MessageItemModelTypeForSystem: {
            SystemMessageViewController *systemVC = [[SystemMessageViewController alloc] init];
            [self.navigationController pushViewController:systemVC animated:YES];
        } break;
        case MessageItemModelTypeForNormal: {
            // 聊天界面
            [self goToServiceChat];
        } break;
        case MessageItemModelTypeForExpert: {
            MineMessageViewController *mineMessageVC = [[MineMessageViewController alloc] init];
            //mineMessageVC.isExpert = YES;
            [self.navigationController pushViewController:mineMessageVC animated:YES];
        } break;
        default:
            break;
    }
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无消息"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    
    [self getDataIfExpert];
}

@end
